#include "comdialog.h"
#include "ui_comdialog.h"

#include "qextserialport.h"
#include "qextserialenumerator.h"
#include "QDebug"
#include "QFile"
#include "serialconnection.h"

int portNum;

COMDialog::COMDialog(SerialConnection *ser, QWidget *parent) :
        QDialog(parent),
        ui(new Ui::COMDialog)
{
    ui->setupUi(this);
    this->setWindowTitle("Connect to COM Port");
    this->ser = ser;
}

COMDialog::~COMDialog()
{
    delete ui;
}

void COMDialog::refreshComports()
{

    QString lastPort;
    QFile file("lastport.txt");
    if(!file.open(QIODevice::ReadOnly | QIODevice::Text)){
        qDebug("Error opening Port History File");
        lastPort="";
    }else{
    QTextStream in(&file);
        lastPort=in.readLine();
    }
    file.close();
    qDebug() << lastPort;

    ui->comboBox_comport->clear();
    // Get all Serial Ports of the System to show them in list
    QList<QextPortInfo> comports = QextSerialEnumerator::getPorts();
    for(int i=0; i < comports.length();i++){
        QString portname = comports[i].portName.left(7);
        while(!portname.right(1)[0].isDigit()){
            portname.chop(1);
        }
        if(portname == lastPort){
            portNum = i;
        }
        ui->comboBox_comport->addItem(portname);
    }
    ui->comboBox_comport->setCurrentIndex(portNum);
}

void COMDialog::on_pushButton_connect_clicked()
{

    portNum = ui->comboBox_comport->currentIndex();
    QString portname = ui->comboBox_comport->itemText(portNum);
    qDebug() << "Open" << portname;

    BaudRateType baudrate = BAUD921600;
    switch(ui->comboBox_baudrate->currentIndex()) {
        case 0:
            baudrate = BAUD921600;
            break;
        case 1:
            baudrate = BAUD460800;
            break;
        case 2:
            baudrate = BAUD256000;
            break;
        case 3:
            baudrate = BAUD115200;
            break;
        case 4:
            baudrate = BAUD57600;
            break;
    }
    qDebug() << baudrate;
    ser->openPort(portname, baudrate);

    QFile file("lastport.txt");
    if(!file.open(QIODevice::WriteOnly | QIODevice::Text)){
        qDebug("Error opening Port History File");
        return;
    }

    QTextStream out(&file);
    out << ui->comboBox_comport->itemText(ui->comboBox_comport->currentIndex());
    file.close();

    ui->comboBox_comport->setEnabled(false);
    ui->comboBox_baudrate->setEnabled(false);
    ui->pushButton_connect->setEnabled(false);
    ui->pushButton_disconnect->setEnabled(true);


}

void COMDialog::on_pushButton_disconnect_clicked()
{
    ser->closePort();

    ui->comboBox_comport->setEnabled(true);
    ui->comboBox_baudrate->setEnabled(true);
    ui->pushButton_connect->setEnabled(true);
    ui->pushButton_disconnect->setEnabled(false);
}
